package common

import (
	"bytes"
	"crypto/tls"
	"database/sql"
	"fmt"
	"gitchina/CPTT4WeChat/data"
	"gitchina/CPTT4WeChat/models"
	"gitchina/CPTT4WeChat/util"
	"io/ioutil"
	"net/http"
)

var domain string
var connStr string
var runmode = "test"
var passwd = "123456"

func InitCommon() {
	util.InitLogger(runmode)
	data.InitOrm(runmode)

	if runmode == "dev" {
		domain = "localhost:8082"
	} else if runmode == "test" {
		domain = "mt.quickly56.com"
	} else if runmode == "uat" {
		//domain = "121.40.179.96:8081"
	}
	var wechat models.WeChat
	wechat.Init()
}

func Domain() string {
	return domain
}

func TruncateTables(tables ...string) {
	db, err := sql.Open("mysql", data.GetConnStr())
	if err != nil {
		panic(err.Error())
	}
	defer db.Close()
	for _, t := range tables {
		_, err = db.Exec(fmt.Sprintf("truncate table %s;", t))
	}
	if err != nil {
		panic(err.Error())
	}
}

func SqlExec(s string) {
	db, err := sql.Open("mysql", data.GetConnStr())
	if err != nil {
		panic(err.Error())
	}
	defer db.Close()
	_, err = db.Exec(s)
	if err != nil {
		panic(err.Error())
	}
}

func HttpCall(method, url string, data []byte, ssl bool) (int, string) {
	var req *http.Request
	if method == "GET" {
		req, _ = http.NewRequest(method, fmt.Sprintf("%s?%s", url, string(data)), nil)
	} else {
		req, _ = http.NewRequest(method, url, bytes.NewBuffer(data))
	}

	var client *http.Client
	if ssl {
		client = &http.Client{Transport: &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}}
	} else {
		client = &http.Client{}
	}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	data, _ = ioutil.ReadAll(resp.Body)
	return resp.StatusCode, string(data)
}

func HttpCallApi(method string, data []byte) (int, string) {
	return HttpCall(method, fmt.Sprintf("http://%s/cz/v1/api/?signature=37580ecbab1ec036dee7aa04ab0dad02993d6a64&timestamp=1471099079&nonce=1296411498&openid=ouPHlv9n4YEVDZ5mbc-r84qsO6NE", Domain()), data, false)
}

func HttpCallUpload(uri string, data []byte) (int, string) {
	return HttpCall("POST", fmt.Sprintf("http://%s/cz/v1/api/%s/", Domain(), uri), data, false)
}
